<?php
namespace Novel\Model;

use Think\Model;

class UserModel extends Model{

    protected $tableName = 'user';

    /**
     * 用户登陆
     */
    public function getUid($oid){
        $where['openid'] = $oid;
        $uid = $this->where($where)->getField('id');
        if(!$uid){
            $data = [
                'nickname'=>C('anonymous_name'),
                'logo'=>C('anonymous_logo'),
                'openid'=>$oid
            ];
            $uid = $this->data($data)->add();
        }
        return $uid;
    }
    /**
     * 用户登陆
     */
    public function getUnionIdByOpenid($oid,$data){
        $where['openid'] = $oid;
        $union_id = M('openid')->where($where)->getField('union_id');
        if(!$union_id){
            if(!empty($data)){
                $data = json_decode(base64_decode($data),true);
                $add = [
                    'openid'=>$oid,
                    'union_id'=>$data['union_id'],
                ];
                M('openid')->data($add)->add();
                $union_id = $data['union_id'];
            }
        }
        return $union_id;
    }
    /**
     * 用户登陆
     */
    public function getUidByUnionId($union_id){
        $where['union_id'] = $union_id;
        $uid = $this->where($where)->getField('id');
        if(!$uid){
            $data = [
                'nickname'=>C('anonymous_name'),
                'logo'=>C('anonymous_logo'),
                'union_id'=>$union_id
            ];
            $uid = $this->data($data)->add();
        }
        return $uid;
    }

    public function addUser($arr,$event_key){
        my_log('addUser:'.json_encode($arr));
        $user = M('user')->where(['union_id'=>$arr['unionid']])->find();
        if($user){
            if(!empty($arr['nickname'])&&!empty($arr['headimgurl'])){
                M('user')
                    ->where(['union_id'=>$arr['unionid']])
                    ->save([
                        'openid'=>$arr['openid'],
                        'nickname'=>$arr['nickname'],
                        'logo'=>$arr['headimgurl'],
                        'sex'=>$arr['sex'],
                    ]);
            }
        }else{
            $data = [
                'nickname'=>$arr['nickname'],
                'logo'=>$arr['headimgurl'],
                'sex'=>$arr['sex'],
                'openid'=>$arr['openid'],
                'union_id'=>$arr['unionid']
            ];
            M('user')->data($data)->add();
        }
        return true;
    }

    /* end of user model */
}
